package com.soulapp.hook.hooker

import android.os.Bundle
import android.widget.Toast
import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.kavaref.condition.type.Modifiers
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator.MemberHookCreator.Result
import com.highcapable.yukihookapi.hook.log.YLog
import com.soulapp.data.ConfigData

// 去除开屏广告
object LimitAdvertHook : BaseHooker() {
    private const val TAG = "LimitAdvertHook"
    private var mainAdHook: Result? = null
    private var splashAdHook: Result? = null

    override fun getKey() = ConfigData.limitAdvert

    override fun onHook() {
        startHook()
    }

    override fun startHook() {
        YLog.debug("startHook $TAG $hookEnabled")
        if (!hookEnabled) return

        // "跳过 %d"
        val hotAdActivity = "cn.soulapp.android.ad.ui.HotAdActivity"
        mainAdHook = hotAdActivity.toClass()
            .resolve()
            .optional()
            .method {
                modifiers(Modifiers.PUBLIC)
                name("onCreate")
                parameters(Bundle::class)
                returnType = Void::class.javaPrimitiveType
            }.first()
            .hook {
                before {
                    // 直接调用 finish 方法跳过广告
                    val showToast = ConfigData.getBoolean(ConfigData.showToast)
                    if (showToast) {
                        Toast.makeText(appContext, "跳过主页广告", Toast.LENGTH_SHORT).show()
                    }
                    this.instance<android.app.Activity>().finish()
                }
            }

        val adViewProvider = "cn.soulapp.android.component.startup.main.AdViewProvider"
        splashAdHook = adViewProvider.toClass()
            .resolve()
            .optional()
            .method {
                modifiers(Modifiers.PUBLIC)
                name("a0")
                parameterCount(1)
                returnType = Void::class.javaPrimitiveType
            }.first()
            .hook {
                replaceUnit {
                    val showToast = ConfigData.getBoolean(ConfigData.showToast)
                    if (showToast) {
                        Toast.makeText(appContext, "跳过开屏广告", Toast.LENGTH_SHORT).show()
                    }
                }
            }
    }

    override fun stopHook() {
        if (hookEnabled) return
        mainAdHook?.let {
            it.remove {
                YLog.debug("stopHook mainAdHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook mainAdHook $TAG 失败")

        splashAdHook?.let {
            it.remove {
                YLog.debug("stopHook splashAdHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook splashAdHook $TAG 失败")
    }

}